# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import fields, models, api

import logging
_logger = logging.getLogger(__name__)


class IotGateway(models.Model):
    _name = "iot.gateway"
    _description = 'IotGateway'
    _order = "name"

    related_user_id = fields.Many2one('res.users', 'Related User',
                                      help="The user for this gateway to login odoo")

    user_id = fields.Many2one('res.users', 'User',
                              default=lambda self: self.env.uid, index=True)

    partner_id = fields.Many2one('res.partner', 'Partner',
                                 related='user_id.partner_id', store=True, index=True)

    company_id = fields.Many2one('res.company', 'Company',
                                 default=lambda self: self.env.company, index=True)

    project_id = fields.Many2one('iot.project', 'Project', index=True)
    device_ids = fields.One2many('iot.device', 'gateway_id', string='Devices')
    sensor_ids = fields.One2many('iot.sensor', 'gateway_id', string='Sensors')

    name = fields.Char(index=True)
    code = fields.Char(index=True)
    router_code = fields.Char(string='Router Code', related='code')

    latitude = fields.Float(string='Latitude', digits=(16, 5))
    longitude = fields.Float(string='Longitude', digits=(16, 5))

    _sql_constraints = [
        ('unique_code', 'UNIQUE (code)',  'Gateway code is unique!'),
        ('related_user_uniq', 'unique (related_user_id )',
         "A user cannot be linked to multiple gateway.")
    ]

    # @api.model
    # @api.returns('self', lambda value: value.id)
    # def find_or_create(self, values):
    #     print('find_or_create,values: ', values )
    #     code = values['code']
    #     domain = [('code', '=', code)]
    #     obj = self.search(domain, limit=1)
    #     print('find_or_create, search: ', obj )
    #     if obj:
    #         return obj

    #     print('find_or_create, create: ' )
    #     return self.create(values)
